package com.oude.httpclient.ui.fragment;


import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.oude.httpclient.R;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cz.msebera.android.httpclient.Header;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class SecondFragment extends Fragment {

    //返回码
    public static final int Success = 200;
    public static final int Fail = 500;
    //下拉表
    private ArrayAdapter<String> adapter_second1, adapter_second2;
    private String server_ip, server_port,access_path01,access_path02;
    private Spinner sp_second1, sp_second2;
    //网页
    private WebView webView;

    public SecondFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_second, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    //初始化布局
    private void initView() {
        //控件绑定
        sp_second1 = getActivity().findViewById(R.id.second_Spinner1);
        sp_second2 = getActivity().findViewById(R.id.second_Spinner2);
        Button bn_visit = getActivity().findViewById(R.id.second_visit);
        webView = getActivity().findViewById(R.id.webView02);
        //下拉表
        //父下拉表，下拉内容固定
        String[] array_second1 = this.getResources().getStringArray(R.array.second_spinner1_item);
        adapter_second1 = new ArrayAdapter<String>(getActivity(), R.layout.spinner_item, array_second1);
        adapter_second1.setDropDownViewResource(R.layout.spinner_down);
        sp_second1.setAdapter(adapter_second1);
        sp_second1.setOnItemSelectedListener(new spinnerListener());
        //绑定控件
        bn_visit.setOnClickListener(new VistiClickListener());

    }

    //下拉表关联实现
    class spinnerListener implements AdapterView.OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> p1, View p2, int p3, long p4) {
            switch (p3) {
                case 0:
                    String[] array_second2 = getActivity().getResources().getStringArray(R.array.second_spinner2_item);
                    adapter_second2 = new ArrayAdapter<String>(getActivity(), R.layout.spinner_item, array_second2);
                    adapter_second2.setDropDownViewResource(R.layout.spinner_down);
                    sp_second2.setAdapter(adapter_second2);
                    break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> p1) {
            // TODO: Implement this method
        }
    }

    //--------各框架访问方法--------
    class VistiClickListener implements View.OnClickListener {
        @Override
        public void onClick(View p1) {
            webView.loadData("loading...", "text/html", "UTF-8");
            //获取设置信息
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
            server_ip = sp.getString("server_ip", "127.0.0.1");
            server_port = sp.getString("server_port", "80");
            access_path01 = sp.getString("access_path01", "");
            access_path02 = sp.getString("access_path02", "");
            //获取下拉表内容
            String[] sp1_array = getResources().getStringArray(R.array.second_spinner1_item);
            String[] sp2_array = getResources().getStringArray(R.array.second_spinner2_item);
            String sp1_value = sp_second1.getSelectedItem().toString();
            String sp2_value = sp_second2.getSelectedItem().toString();
            //HTTPClient访问
            if (sp1_value.equals(sp1_array[0])) {
                if (sp2_value.equals(sp2_array[0])) {
                    OkHttp3Test(0);
                }
                if (sp2_value.equals(sp2_array[1])) {
                    OkHttp3Test(1);
                }
            }
            //HttpURLConnection访问
            if (sp1_value.equals(sp1_array[1])) {
                if (sp2_value.equals(sp2_array[0])) {
                    AsyncHttpClientTest(0);
                }
                if (sp2_value.equals(sp2_array[1])) {
                    AsyncHttpClientTest(1);
                }
            }

        }
    }


    //根据返回码判断反馈是否发送成功
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Success:
                    Log.i("FirstFragment-HTTPClientTest-Handle", "返回内容：" + msg.obj);
                    webView.loadData(String.valueOf(msg.obj), "text/html", "UTF-8");
                    break;
                case Fail:
                    webView.loadData("访问失败！", "text/html", "UTF-8");
                    break;
                default:
                    break;
            }
        }
    };

    //OkHttp3
    private void OkHttp3Test(final Integer flag) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = "";
                String targetUrl = "";
                switch (flag) {
                    case 0:
                        targetUrl = "http://" + server_ip + ":" + server_port + access_path01;
                        break;
                    case 1:
                        targetUrl = "http://" + server_ip + ":" + server_port + access_path02;
                        break;
                }
                Log.i("FirstFragment-OkHttp3-targetUrl", "targetUrl：" + targetUrl);
                OkHttpClient client = new OkHttpClient();
                //设置超时时间
                client.newBuilder().connectTimeout(5, TimeUnit.SECONDS).readTimeout(5, TimeUnit.SECONDS).build();

                //使用request，并指定GET方法
                Request request = new Request.Builder().get().url(targetUrl).build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    result = response.body().string();
                    Log.i("FirstFragment-OkHttp3-result", "内容：" + result);
                    if (result != "") {
                        Message OkHttp3Message = new Message();
                        OkHttp3Message.obj = result;
                        handler.obtainMessage(Success, result).sendToTarget();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = Fail;
                    handler.sendMessage(message);
                }

            }
        }).start();
    }

    //AsyncHttpClient
    private void AsyncHttpClientTest(final Integer flag) {
        String targetUrl = "";
        switch (flag) {
            case 0:
                targetUrl = "http://" + server_ip + ":" + server_port + access_path01;
                break;
            case 1:
                targetUrl = "http://" + server_ip + ":" + server_port + access_path02;

                break;
        }
        Log.i("FirstFragment-AsyncHttpClient-targetUrl", "targetUrl：" + targetUrl);
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(targetUrl, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                StringBuffer bufferr = new StringBuffer("");
                int length = responseBody.length;
                for (int i = 0; i < length; i++) {
                    bufferr.append((char) (responseBody[i] & 0xff));
                }
                String result = bufferr.toString();
                Log.i("FirstFragment-AsyncHttpClientTest-result", "内容：" + result);
                if (result != "") {
                    webView.loadData(result, "text/html", "UTF-8");
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                webView.loadData("访问失败！", "text/html", "UTF-8");
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onRetry(int retryNo) {
                super.onRetry(retryNo);
            }

            @Override
            public void onCancel() {
                super.onCancel();
            }
        });
    }

}
